package net.maku.module.controller;

import com.aliyuncs.utils.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.framework.operatelog.annotations.OperateLog;
import net.maku.framework.operatelog.enums.OperateTypeEnum;
import net.maku.framework.security.user.SecurityUser;
import net.maku.framework.security.user.UserDetail;
import net.maku.module.dao.AgContentDao;
import net.maku.module.entity.AgContent;
import net.maku.module.entity.AgContentLink;
import net.maku.module.entity.AgContentLogEntity;
import net.maku.module.service.AgContentLinkService;
import net.maku.module.service.AgContentService;
import net.maku.module.util.UrlReplaceUtil;
import net.maku.module.vo.AgContentCombined;
import net.maku.storage.service.StorageService;
import net.maku.system.vo.SysFileUploadVO;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/content")
@Tag(name = "内容管理")
@AllArgsConstructor
public class AgContentController {
    private final StorageService storageService;

    private final AgContentService agContentService;
    private final AgContentLinkService agContentLinkService;
    private final AgContentDao agContentDao;

    @Autowired
    private UrlReplaceUtil urlReplaceUtil;

    @PostMapping("/upload")
    @Operation(summary = "上传图片")
    @OperateLog(type = OperateTypeEnum.INSERT)
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> response = new HashMap<>();
        if (file.isEmpty()) {
            response.put("errno", 1); // 失败
            response.put("message", "请选择需要上传的文件");
            return response;
        }

        try {
            // 上传路径
            String path = storageService.getPath(file.getOriginalFilename());
            // 上传文件
            String url = storageService.upload(file.getBytes(), path);

            // 成功返回
            Map<String, Object> data = new HashMap<>();
            data.put("url", url); // 必须
            data.put("alt", file.getOriginalFilename()); // 非必须
            data.put("href", url); // 非必须

            response.put("errno", 0); // 成功
            response.put("data", data);
        } catch (Exception e) {
            response.put("errno", 1); // 失败
            response.put("message", "文件上传失败：" + e.getMessage());
        }

        return response;
    }
    @Operation(summary = "保存内容或链接")
    @PostMapping("/saveContent")
    public Result<String> saveContent(@RequestBody List<AgContentCombined> agContentCombinedList) {

        for (AgContentCombined agContentCombined : agContentCombinedList) {
            agContentCombined.setIsShow(0);
            if (!StringUtils.isEmpty(agContentCombined.getImageUrl())) {
                agContentCombined.setImageUrl(StringEscapeUtils.unescapeHtml4(agContentCombined.getImageUrl()));
            }

            if (!StringUtils.isEmpty(agContentCombined.getContent())) {
                agContentCombined.setContent(StringEscapeUtils.unescapeHtml4(agContentCombined.getContent()));
            }
            if (!StringUtils.isEmpty(agContentCombined.getHref())) {
                String href = agContentCombined.getHref();
                // 将 &amp; 恢复成 &
                href = href.replace("&amp;", "&");
                agContentCombined.setHref(href);
            }
            int i = agContentService.saveContent(agContentCombined);
            if (i <= 0) {

                return Result.error("保存失败");
            }
        }
        UserDetail user = SecurityUser.getUser();
        AgContentLogEntity agContentLogEntity = new AgContentLogEntity();
        agContentLogEntity.setType(1);
        agContentLogEntity.setModuleName("内容管理-新增-成功");
        agContentLogEntity.setSuccess(1);
        agContentLogEntity.setUserId(Math.toIntExact(user.getId()));
        agContentService.insertLog(agContentLogEntity);
        return Result.ok("保存成功");
    }

    @Operation(summary = "根据id修改内容发布状态")
    @PostMapping("/updateStatusByContentId")
    public Result<String> updateStatusByContentId(@RequestBody AgContentCombined agContentCombined){
        agContentService.updateStatusByContentId(agContentCombined);
        return Result.ok("修改成功");
    }
    @Operation(summary = "修改内容或链接")
    @PostMapping("/updateContent")
    public Result<String> updateContent(@RequestBody AgContentCombined agContentCombined ){
        agContentCombined.setImageUrl(StringEscapeUtils.unescapeHtml4(agContentCombined.getImageUrl()));
        if (!StringUtils.isEmpty(agContentCombined.getContent())) {
            agContentCombined.setContent(StringEscapeUtils.unescapeHtml4(agContentCombined.getContent()));
        }
        int i =  agContentService.updateContent(agContentCombined);
        if(i>0){
            UserDetail user = SecurityUser.getUser();
            AgContentLogEntity agContentLogEntity = new AgContentLogEntity();
            agContentLogEntity.setType(2);
            agContentLogEntity.setModuleName("内容管理-修改-成功");
            agContentLogEntity.setSuccess(1);
            agContentLogEntity.setUserId(Math.toIntExact(user.getId()));
            agContentService.insertLog(agContentLogEntity);
            return Result.ok("成功");
        }else {
            UserDetail user = SecurityUser.getUser();
            AgContentLogEntity agContentLogEntity = new AgContentLogEntity();
            agContentLogEntity.setType(2);
            agContentLogEntity.setModuleName("内容管理-修改-失败");
            agContentLogEntity.setSuccess(2);
            agContentLogEntity.setUserId(Math.toIntExact(user.getId()));
            agContentService.insertLog(agContentLogEntity);
            return Result.error("失败");
        }
    }
    @PostMapping("/updateTaskInterval")
    public Result<String> updateTaskInterval(@RequestParam long interval) {
        // 调用服务更新定时任务时间间隔
        agContentService.updateFixedRate(interval);
        return Result.ok("定时任务间隔更新成功");
    }

    @Operation(summary = "批量删除内容")
    @PostMapping("/deleteContent")
    public Result<String> deleteContent(@RequestBody List<AgContentCombined> agContentCombinedList) {
        try {
            if (agContentCombinedList == null || agContentCombinedList.isEmpty()) {
                return Result.error("请求参数不能为空");
            }

            // 提取ID列表
            List<Integer> ids = agContentCombinedList.stream()
                    .map(AgContentCombined::getId)
                    .toList();


            // 执行批量删除
            int rowsAffected = agContentService.deleteBatch(ids);


            if (rowsAffected > 0) {
                UserDetail user = SecurityUser.getUser();
                AgContentLogEntity agContentLogEntity = new AgContentLogEntity();
                agContentLogEntity.setType(3);
                agContentLogEntity.setSuccess(1);
                agContentLogEntity.setUserId(Math.toIntExact(user.getId()));
                agContentService.insertLog(agContentLogEntity);
                return Result.ok("成功删除" + rowsAffected + "条记录");
            } else {
                return Result.error("未删除任何记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除过程中发生错误: " + e.getMessage());
        }
    }
    @GetMapping("/selectContent")
    @Operation(summary = "分页查询内容列表")
    public Result<PageResult<AgContentCombined>> selectContent(@RequestParam(required = false) Integer templateType,
                                                               @RequestParam Integer websiteId,
                                                               @RequestParam(required = false) Integer id,
                                                               @RequestParam(required = false) String title,
                                                               @RequestParam(defaultValue = "1") Integer pageNum,
                                                               @RequestParam(defaultValue = "10") Integer pageSize,
                                                               @RequestParam(required = false) String approveState
    ) throws Exception {
       PageResult pageResult =  agContentService.selectContent(templateType,title,pageNum,pageSize,id,websiteId,approveState);
       return Result.ok(pageResult);
    }
    @GetMapping("/selectShowContent")
    @Operation(summary = "查询展示首页的内容列表")
    public Result<List<AgContentCombined>> selectShowContent(@RequestParam Integer websiteId){
       List<AgContentCombined> list = agContentService.selectShowContent(websiteId);
        return Result.ok(list);
    }
    @GetMapping("/selectNotShowContent")
    @Operation(summary = "查询未展示首页的内容列表")
    public Result<PageResult<AgContentCombined>> selectNotShowContent(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize,@RequestParam Integer websiteId){
        PageResult pageResult =  agContentService.selectNotShowContent(pageNum,pageSize,websiteId);
        return Result.ok(pageResult);
    }
    @GetMapping("/updateShow")
    @Operation(summary = "根据id直接修改展示状态")
    public Result updateShow(@RequestParam Integer id,@RequestParam Integer show,@RequestParam Integer websiteId) {
        // 如果展示内容为1，即展示状态
        if (show == 1) {
            // 获取当前已展示的内容
            List<AgContentCombined> agContentCombineds = agContentService.selectShowContent(websiteId);

            // 判断是否已超过最大展示数量限制
           /* if (agContentCombineds.size() >= 3) {
                return Result.error("已超过最大展示内容数量限制");
            }*/
        }

        // 更新展示状态
        boolean updateSuccess = agContentService.updateShow(id, show) > 0;

        // 返回结果
        return updateSuccess ? Result.ok() : Result.error("未知异常");

    }
    @GetMapping("/selectContentById")
    @Operation(summary = "根据子栏目id分页查询内容")
    public Result<Map<String, Object>> selectContentById(HttpServletRequest request,
            @RequestParam Integer id,
                                                         @RequestParam Integer type,
                                                         @RequestParam Integer webSiteId,
                                                         @RequestParam(defaultValue = "1") int page,
                                                         @RequestParam(defaultValue = "20") int pageSize) {

        Map<String, Object> resultMap = agContentService.selectContentByIdWithPage(request,id, type, webSiteId, page, pageSize);

        // 对特殊栏目id排序逻辑（如果仍需要按 sort 排序，可以在这里处理）
        List<AgContentCombined> list = (List<AgContentCombined>) resultMap.get("data");
        if (id == 1902 || id == 1900) {
            list = list.stream()
                    .sorted(Comparator.comparing(AgContentCombined::getSort).reversed())
                    .collect(Collectors.toList());
        } else if(id == 1986) {

        } else {
            //去调时间排序
            list = list.stream()
                    .sorted(Comparator.comparing(AgContentCombined::getSort))
                    .collect(Collectors.toList());
        }
        resultMap.put("data", list);

        return Result.ok(resultMap);
    }
    @GetMapping("/searchFull")
    @Operation(summary = "全文搜索（假）")
    public Result<PageResult<AgContentCombined>> searchFull(@RequestParam String text,
                                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                                            @RequestParam(defaultValue = "10") Integer pageSize,
                                                            @RequestParam Integer websiteId) {
        // 调用 Service 层的分页查询方法
        PageResult<AgContentCombined> pageResult = agContentService.searchFull(text, pageNum, pageSize,websiteId);

        // 返回分页结果
        return Result.ok(pageResult);
    }
    @GetMapping("/selectContentLogs")
    @Operation(summary = "内容管理日志查询")
    public Result<PageResult<AgContentLogEntity>> searchFull(@RequestParam(required = false) Integer type,@RequestParam(required = false) Integer success,
                                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 调用 Service 层的分页查询方法
        PageResult<AgContentLogEntity> pageResult = agContentService.selectContentLogs(type,success, pageNum, pageSize);

        // 返回分页结果
        return Result.ok(pageResult);
    }

    @GetMapping("/getHomeContent")
    @Operation(summary = "网站获取首页内容")
    public Result<List<AgContentCombined>> getHomeContent(HttpServletRequest request){
        List<AgContentCombined> list =  agContentService.getHomeContent();
        urlReplaceUtil.replaceImageUrlsContent(request,list);
        urlReplaceUtil.replaceContent(request,list);

        return Result.ok(list);


    }
    @GetMapping("/getAnnouncement")
    @Operation(summary = "网站获取公告内容")
    public Result<List<AgContentCombined>> getAnnouncement(HttpServletRequest request){
        List<AgContentCombined> list =  agContentService.getAnnouncement();
        urlReplaceUtil.replaceContent(request,list);
        return Result.ok(list);


    }
    @GetMapping("/queryById")
    @Operation(summary = "根据id查询内容详情")
    public Result<AgContentCombined> queryById(HttpServletRequest request,@RequestParam Integer id){
      AgContentCombined agContentCombined =  agContentService.queryById(id);
        List<AgContentCombined> res = new ArrayList();
        res.add(agContentCombined);
        urlReplaceUtil.replaceContent(request,res);

      return Result.ok(agContentCombined);
    }
    @GetMapping("/getSortIsOne")
    @Operation(summary = "根据栏目id获取置顶内容")
    public Result<AgContentCombined> getSortIsOne(HttpServletRequest request,@RequestParam Integer id){
        AgContentCombined agContentCombined = agContentService.getSortIsOne(id);
        List<AgContentCombined> res = new ArrayList();
        res.add(agContentCombined);
        urlReplaceUtil.replaceContent(request,res);
        urlReplaceUtil.replaceImageUrlsContent(request,res);
        return Result.ok(res.get(0));
    }
}

